#include "crc_check.h"
#include "board.h"

void InvertUint8(unsigned char *dBuf, unsigned char *srcBuf)
{
    int i;
    unsigned char tmp[4];
    tmp[0] = 0;
    for (i = 0; i < 8; i++) {
        if (srcBuf[0] & (1 << i)) tmp[0] |= 1 << (7 - i);
    }
    dBuf[0] = tmp[0];
}
void InvertUint16(unsigned short *dBuf, unsigned short *srcBuf)
{
    int i;
    unsigned short tmp[4];
    tmp[0] = 0;
    for (i = 0; i < 16; i++) {
        if (srcBuf[0] & (1 << i)) tmp[0] |= 1 << (15 - i);
    }
    dBuf[0] = tmp[0];
}
void InvertUint32(unsigned int *dBuf, unsigned int *srcBuf)
{
    int i;
    unsigned int tmp[4];

    tmp[0] = 0;

    for (i = 0; i < 32; i++) {
        if (srcBuf[0] & (1 << i)) tmp[0] |= 1 << (15 - i);
    }
    dBuf[0] = tmp[0];
}
uint16_t CRC16_IBM(unsigned char *puchMsg, unsigned int usDataLen)
{
    unsigned short wCRCin = 0x0000;
    unsigned short wCPoly = 0x8005;
    unsigned char wChar = 0;
    uint16_t i = 0;
    while (usDataLen--) {
        wChar = *(puchMsg++);
        InvertUint8(&wChar, &wChar);
        wCRCin ^= (wChar << 8);
        for (i = 0; i < 8; i++) {
            if (wCRCin & 0x8000)
                wCRCin = (wCRCin << 1) ^ wCPoly;
            else
                wCRCin = wCRCin << 1;
        }
    }
    InvertUint16(&wCRCin, &wCRCin);
    return (wCRCin);
}

uint16_t Modbus_CRC16(uint8_t *arr_buff, uint16_t len)
{
    uint16_t crc = 0xFFFF;
    uint16_t i, j;
    for (j = 0; j < len; j++) {
        crc = crc ^ *arr_buff++;
        for (i = 0; i < 8; i++) {
            if ((crc & 0x0001) > 0) {
                crc = crc >> 1;
                crc = crc ^ 0xa001;
            } else
                crc = crc >> 1;
        }
    }
	mprintf(LOG_INFO, "crc is:%x.\r\n", crc);
    return (crc);
}
